package com.dycc.libary.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;

import java.util.Stack;

/**
 * Created by wxk on 2018/1/20 0020.
 */

public class NormalActivityStack {
        private static Stack<Activity> activityStack=new Stack<>();
        private static  NormalActivityStack stackManager;
        private  NormalActivityStack(){}
        public static  NormalActivityStack iniStack(){
                if (activityStack==null)stackManager=new NormalActivityStack();
                return  stackManager;
        }

    /**
     * 添加activity
     */
        public void addActivity(Activity activity){
                activityStack.push(activity);
        }

        /**
         * 获取当前Activity（堆栈中最后一个压入的）
         */
        public Activity currentActivity() {
                return activityStack.lastElement();
        }



        /**
         * 结束指定类名的Activity
         */
        public void finishActivity(Class<?> cls) {
                for (Activity activity : activityStack) {
                        if (activity.getClass().equals(cls)) {
                                finishActivity(activity);
                        }
                }
        }

        /**
         * 结束指定的Activity
         */
        public void finishActivity(Activity activity) {
                if (activity != null) {
                        activityStack.remove(activity);
                        if (!activity.isFinishing()) {
                                activity.finish();
                        }
                }
        }

        /**
         * 结束所有Activity
         */
        public void finishAllActivity() {
                for (Activity activity : activityStack) {
                        if (activity != null) {
                                activity.finish();
                        }
                }
                activityStack.clear();
        }

        /**
         * 退出应用程序
         */
        public void AppExit(Context context) {
                try {
                        finishAllActivity();
                        ActivityManager manager = (ActivityManager) context
                                .getSystemService(Context.ACTIVITY_SERVICE);
                        manager.killBackgroundProcesses(context.getPackageName());
                        System.exit(0);
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}
